package com.atguigu.yygh.user.service.impl;

import com.atguigu.yygh.common.exception.ziDyException;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.PatientService;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.Console;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2021-12-15
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private PatientService patientService;

    @Override
    public Map<String, Object> login(LoginVo loginVo) {

        //1.获取要使用得数据
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        String openid = loginVo.getOpenid();

        //2.验证数据是否为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
            throw new ziDyException(20001,"数据验证失败");
        }

        //TODO 3.手机验证码验证
        String ycode = redisTemplate.opsForValue().get(phone);
        System.out.println("ycode = " + ycode);
        if(!code.equals(ycode)){
            throw new ziDyException(20001,"验证码错误");
        }

        //如果openid是null的话，就证明是在手机登录，如果不是的话就是在绑定手机号
        if(StringUtils.isEmpty(openid)) {

            //验证是否为新用户，如果是新用户得话直接注册，否则就是登录
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("phone",phone);
            UserInfo userInfo = baseMapper.selectOne(wrapper);
            if(userInfo == null){
                userInfo = new UserInfo();
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }

            //查询手机号是否被禁用
            if(userInfo.getStatus() == 0){
                throw new ziDyException(20001,"手机号已经被禁用了");
            }


            Map<String, Object> map = get(userInfo);
            return map;
        } else {
            //如果走了else 证明是在绑定手机号
            //首先根据手机号查询数据库是否有这个手机号的数据
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("phone",phone);
            UserInfo userInfo = baseMapper.selectOne(wrapper);
            //如果userInfo为空，则直接修改添加手机号就可以，如果不为空，将两条数据合并
            if (userInfo == null){
                //则直接修改数据添加手机号
                //使用openid查询出这条数据
                QueryWrapper<UserInfo> phoneWrapper = new QueryWrapper<>();
                phoneWrapper.eq("openid",openid);
                UserInfo userInfo1 = baseMapper.selectOne(phoneWrapper);
                userInfo1.setPhone(phone);
                //修改添加手机号
                baseMapper.updateById(userInfo1);
                Map<String, Object> map = get(userInfo1);

                return map;
            } else {

                //使用openid查询出来这条数据
                //将两条数据合并
                QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("openid",openid);
                UserInfo userInfo1 = baseMapper.selectOne(queryWrapper);
                //查询手机号是否被禁用
                if(userInfo1.getStatus() == 0){
                    throw new ziDyException(20001,"账号已经被禁用了");
                }
                //将phone那条数据合并到openid这条数据中
                userInfo1.setPhone(userInfo.getPhone());
                //用户真实姓名
                userInfo1.setName(userInfo.getName());
                userInfo1.setCertificatesType(userInfo.getCertificatesType());
                userInfo1.setCertificatesNo(userInfo.getCertificatesNo());
                userInfo1.setCertificatesUrl(userInfo.getCertificatesUrl());

                //删除phone那条数据
                baseMapper.delete(new QueryWrapper<UserInfo>().eq("phone",phone));

                //将数据进行修改
                baseMapper.updateById(userInfo1);
                Map<String, Object> map = get(userInfo1);

                return map;
            }


        }
    }


    private Map<String,Object> get(UserInfo userInfo) {
        //返回页面显示名称
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        //根据userid和name生成token字符串
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        return map;
    }
    @Override
    public UserInfo getByOpenId(String openid) {

        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("openid",openid);

        UserInfo userInfo = baseMapper.selectOne(wrapper);

        return userInfo;
    }

    //后台管理用户列表，
    @Override
    public Page<UserInfo> findAllPageUser(Long page, Long limit, UserInfoQueryVo userInfoQueryVo) {

        //设置分页条件
        Page<UserInfo> page1 = new Page<>(page,limit);

        //UserInfoQueryVo获取条件值
        //将使用的条件取出来
        String name = userInfoQueryVo.getKeyword(); //用户名称
        Integer status = userInfoQueryVo.getStatus();//用户状态
        Integer authStatus = userInfoQueryVo.getAuthStatus(); //认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin(); //开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd(); //结束时间


        //对条件值进行非空判断
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("name",name);
        }
        if(!StringUtils.isEmpty(status)) {
            wrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)) {
            wrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }

        //进行查询
        Page<UserInfo> userInfoPage = baseMapper.selectPage(page1, wrapper);

        //将查询到的数据中的编码转换成中文
        userInfoPage.getRecords().stream().forEach(item ->{
            this.packageUserInfo(item);
        });
        return userInfoPage;
    }

    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //使用用户id查询出这条用户数据
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("id",userId);
        UserInfo userInfo = baseMapper.selectOne(wrapper);

        //认证人姓名
        userInfo.setName(userAuthVo.getName());
        //其他认证信息
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());

        baseMapper.updateById(userInfo);
    }

    @Override
    public void updateStatus(Long userId, Integer status) {
        //首先根据userid查询
        UserInfo userInfo = baseMapper.selectById(userId);

        userInfo.setStatus(status);

        baseMapper.updateById(userInfo);
    }

    //查询用户详情
    @Override
    public Map<String, Object> findUserPatient(Long userId) {

        Map<String, Object> map = new HashMap<>();
        //查询用户
        UserInfo userInfo = baseMapper.selectById(userId);
        map.put("userInfo",userInfo);

        //查询就诊人信息
        List<Patient> patient = patientService.findByUserIdPatient(userId);
        map.put("patientList",patient);
        return map;
    }

    @Override
    public void updateAuthStatus(Long userId, Integer authStatus) {
        //查询出这条数据
        UserInfo userInfo = baseMapper.selectById(userId);

        //修改数据
        userInfo.setAuthStatus(authStatus);

        //根据id进行修改数据
        baseMapper.updateById(userInfo);
    }

    //编号变成对应值封装
    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue()==0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }

}
